package cn.gailvlun.gll.presentation.apartment;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.databinding.ActivityApartmentListBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.ListRes;
import cn.gailvlun.gll.presentation.apartment.adapter.ApartmentListAdapter;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.net.apartment.room.GetRoomListReq;
import cn.gailvlun.gll.net.apartment.room.Room;
import cn.gailvlun.gll.net.apartment.room.RoomTag;
import cn.gailvlun.gll.net.apartment.room.RoomType;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.widget.NavigationBarView;



public class ApartmentListActivity extends BaseActivity implements OnRefreshListener, OnLoadmoreListener {

    public static void openActivity(Context context, boolean isCp, @Nullable RoomTag roomTag) {
        Intent intent = new Intent(context, ApartmentListActivity.class);
        intent.putExtra("isCp", isCp);
        if (!isCp) {
            intent.putExtra("tag", roomTag);
        }
        context.startActivity(intent);
    }

    private ActivityApartmentListBinding mBinding;

    private ApartmentListAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;

    private GetRoomListReq mGetRoomListReq = new GetRoomListReq();
    {
        mGetRoomListReq.setType(RoomType.tag);
    }

    private boolean isCp;

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_apartment_list);

        mAdapter = new ApartmentListAdapter(mContext);
        mAdapter.setPresenter(new Presenter());
        mBinding.recyclerView.setAdapter(mAdapter);

        mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.recyclerView.setLayoutManager(mLayoutManager);

        mBinding.refreshLayout.setOnRefreshListener(this);
        mBinding.refreshLayout.setOnLoadmoreListener(this);
        mBinding.refreshLayout.setEnableLoadmore(false);

        isCp = getIntent().getBooleanExtra("isCp", false);
        
        if (isCp) {
            mBinding.rgTag.setVisibility(View.VISIBLE);
            String[] cpColumns = getResources().getStringArray(R.array.apartment_cp_column);
            List<String> columnList = Arrays.asList(cpColumns);
            String[] cpTags = getResources().getStringArray(R.array.apartment_cp_tag);
            final List<RoomTag> tagList = new ArrayList<>();
            for (String tag :
                    cpTags) {
                tagList.add(RoomTag.valueOf(tag));
            }

            
            for (int i = 0; i < columnList.size(); i++) {
                ((RadioButton) mBinding.rgTag.getChildAt(i)).setText(columnList.get(i));
            }

            mBinding.rgTag.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    int position = group.indexOfChild(group.findViewById(checkedId));

                    mGetRoomListReq.setRoom_tag(tagList.get(position));
                    mBinding.refreshLayout.autoRefresh(0);
                }
            });

            mBinding.rgTag.check(mBinding.rgTag.getChildAt(0).getId());
        } else {
            RoomTag tag = (RoomTag) getIntent().getSerializableExtra("tag");
            mGetRoomListReq.setRoom_tag(tag);
        }
    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
    }

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        if (!isCp) {
            mBinding.refreshLayout.autoRefresh(0);
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mGetRoomListReq.resetPage();
        HttpMethods.getRoomService()
                .getRoomList(mGetRoomListReq.getDirection(), mGetRoomListReq.getId(),
                        mGetRoomListReq.getType(), mGetRoomListReq.getRoom_tag() == null ? null : mGetRoomListReq.getRoom_tag().name())
                .compose(RxUtil.<ListRes<Room>>applyScheduler())
                .subscribe(new HttpSubscriber<ListRes<Room>>() {
                    @Override
                    protected void onSuccess(ListRes<Room> response) {
                        mBinding.refreshLayout.finishRefresh();
                        loadRecyclerView(response.getResults(), true, response.isNext());
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Room> response, int code) {
                        mBinding.refreshLayout.finishRefresh();
                    }
                });
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mGetRoomListReq.nextPage(mAdapter.getLastRoomId());
        HttpMethods.getRoomService()
                .getRoomList(mGetRoomListReq.getDirection(), mGetRoomListReq.getId(),
                        mGetRoomListReq.getType(), mGetRoomListReq.getRoom_tag() == null ? null : mGetRoomListReq.getRoom_tag().name())
                .compose(RxUtil.<ListRes<Room>>applyScheduler())
                .subscribe(new HttpSubscriber<ListRes<Room>>() {
                    @Override
                    protected void onSuccess(ListRes<Room> response) {
                        mBinding.refreshLayout.finishRefresh();
                        loadRecyclerView(response.getResults(), false, response.isNext());
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Room> response, int code) {
                        mBinding.refreshLayout.finishRefresh();
                        DialogUtil.showError(mContext, errMsg);
                    }
                });
    }

    private void loadRecyclerView(List<Room> list, boolean isRefresh, boolean isMore) {
        if (isRefresh) {
            mAdapter.clear();
            if (IsEmpty.list(list)) {

            } else {
                mAdapter.addAll(list);
            }
        } else {
            mAdapter.addAll(list);
        }

        mBinding.refreshLayout.setEnableLoadmore(isMore);
    }

    public class Presenter implements BaseViewAdapter.Presenter {
        public void enterRoom(Room item) {
            ApartmentDetailActivity.openActivity(mContext, item.getId());
        }
    }
}
